package com.aizu.controller;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.aizu.common.Constant;
import com.aizu.entity.User;
import com.aizu.service.ERentService;
import com.aizu.service.MasterService;
import com.aizu.service.RenterService;
import com.aizu.service.SmsService;
import com.aizu.utils.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.isp.jdbc.model.Pager;

@Controller
@RequestMapping(value = Constant.PATH_RENTER)
public class RenterController extends CommonController {

	private Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private RenterService renterService;
	@Autowired
	private MasterService masterService;
	@Autowired
	private SmsService smsService;
	@Autowired
	private ERentService eRentService;

	/** 请求上下文全路径 */
	@Value("${aizu.basePath}")
	private String basePath;
	/** eRent接口路径 */
	@Value("${eRent.basePath}")
	private String eRentPath;

	@RequestMapping(value = "/{page}.html")
	public ModelAndView index(@PathVariable("page") String page) {
		return modelAndView(Constant.PATH_RENTER + page);
	}

	/**
	 * 生成4位随机码<br />
	 * 验证手机号是否已存在，存在则不发验证码
	 */
	@Override
	@RequestMapping(value = "/getCode.htm")
	@ResponseBody
	protected String getCode(String phone, HttpServletRequest request, HttpServletResponse response) {
		String idcard = request.getParameter("idcard");
		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("phone", phone);
		map.put("idcard", idcard);
		if (StringUtils.isBlank(idcard)) {
			log.debug("身份证号都不能为空");
			this.toJson(response, "身份证号都不能为空");
			return null;
		}
		try {
			User user = this.renterService.loadUser(map);
			if (null == user) {
				log.debug("身份证没有本系统内登记，不能发验证码。idcard:" + idcard);
				this.toJson(response, "身份证还没登记，无法发送验证码");
				return null;
//			} else if (null != user && StringUtils.isNotBlank(user.getFromUserName())) {
//				log.debug("手机号已被绑定，请先解绑或输入其它手机号");
//				this.toJson(response, "手机号已被绑定，请先解绑或输入其它手机号");
//				return null;
			}
			log.info("原手机号：" + user.getUserPhone() + ", 当前获取验证码手机号：" + phone);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.getCode(phone, request, response);
	}

	@RequestMapping(value = "/register.htm")
	public String register(HttpServletRequest request, HttpServletResponse response) {
		String fromUserName = getFromUserName(request);
		String code = request.getParameter("code");
		if (!BooleanUtils.toBoolean(validateCode(code, true, request))) {
			// 验证不通过
			return redirect(Constant.PATH_RENTER + "register.html", request);
		}

		String nameL = request.getParameter("nameL");
		String phone = request.getParameter("phone");
		String idcard = request.getParameter("idcard");
		if (StringUtils.isNotBlank(idcard))
			idcard = idcard.toUpperCase();// 身份证的字母都要是大写
		String enote = request.getParameter("enote");
		log.debug("name: " + nameL + ", phone: " + phone + ", idcard: " + idcard + ", enote: " + enote + ", code: "
				+ code);

		User renter = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("idcard", idcard);

		try {
			renter = this.renterService.loadUser(map);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		map.put("nameL", nameL);
		map.put("phone", phone);
		map.put("enote", enote);
		map.put("create_date", new Date());
		map.put("wx_userid", fromUserName);
		if (null == renter) {
			// 现在我们系统不能新增，只能通过接口让别人主动推送房客信息过来
			// try {
			// renter = renterService.saveUser(map);
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			log.info("此身份证号码还没有推送到本系统");
			alert("此身份证号码还没有推送到本系统", request);
		} else if (StringUtils.isNotBlank(fromUserName)) {
			renter.setFromUserName(fromUserName);
			try {
				Map<String, String> postParam = new HashMap<String, String>();
				postParam.put("phone", phone);// 手机号码MD5加密
				postParam.put("wxNum", fromUserName);// 微信号码
				postParam.put("twoCard", idcard);// 身份证号码MD5加密
				postParam.put("dzLabel", enote);// 电子标签号
				String jsonStr = HttpUtils.post(eRentPath + "wxRegister/wxKRegister", postParam);
				log.info("接口房客注册结果：" + jsonStr);
				// 读取JSON数据
				// ObjectMapper mapper = new ObjectMapper();
				// Map<String, Object> json=mapper.readValue(jsonStr,Map.class);
				Map<String, Map<String, String>> json = (Map<String, Map<String, String>>) JSON.parse(jsonStr);
				Map<String, String> result = (Map<String, String>) json.get("result");
				String flag = result.get("flag");
				if ("0".equals(flag)) {
					map.put("id", renter.getUserId());
					renterService.updateEnote(map);
					if (StringUtils.isNotBlank(phone) && !phone.equals(renter.getUserPhone()))// 如果手机号不一致，则更换手机号
						renter.setUserPhone(phone);
					renterService.updateUser(renter);
				} else {
					log.info("接口注册失败，本地不进行注册。");
					alert(result.get("msg"), request);
					renter = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
				alert("注册失败", request);
				renter = null;
			}
		}

		if (null != renter) {
			request.getSession().setAttribute(RENTER, renter);
			map.put("namel", (String) map.get("nameL"));
			map.put("phoneHidden", renter.getUserPhone().replaceAll("(.+).{4}(.{4})", "$1****$2"));
			map.put("idcardHidden", ((String) map.get("idcard")).replaceAll("(.+).{10}(.{4})", "$1**********$2"));
			request.getSession().setAttribute("renterInfo", map);

			// returnredirect(Constant.PATH_RENTER+"communityList.htm",request);
			return redirect(Constant.PATH_RENTER + "userInfo.html", request);
		}

		
		
		return redirect(Constant.PATH_RENTER + "register.html", request);
	}

	@RequestMapping(value = "/userInfo.htm")
	public String userInfo(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		String fromUserName = getFromUserName(request);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("wx_userid", fromUserName);
		try {
			List<Map<String, Object>> renterList = this.renterService.findRenter(map);
			if (null != renterList && !renterList.isEmpty()) {
				Map<String, Object> renterInfo = renterList.get(0);
				renterInfo.put("phoneHidden",
						((String) renterInfo.get("phone")).replaceAll("(.+).{4}(.{4})", "$1****$2"));
				renterInfo.put("idcardHidden",
						((String) renterInfo.get("idcard")).replaceAll("(.+).{10}(.{4})", "$1**********$2"));
				request.setAttribute("renterInfo", renterInfo);
			} else {
				return this.redirect(Constant.PATH_RENTER + "register.html", request);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return this.forward(Constant.PATH_RENTER + "userInfo.html");
	}

	/**
	 * 只重绑标签
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/reRegister.htm")
	public String reRegister(HttpServletRequest request, HttpServletResponse response) {
		// 解绑（可以不解绑，直接重新绑定）
		if (StringUtils.isNotBlank(request.getParameter("enote"))) {
			// 如果有旧便签，才要解绑
			Map<String, String> delCRegisterResult = delCRegister(request, response);
			if ("1".equals(delCRegisterResult.get("flag"))) {
				alert(delCRegisterResult.get("msg"), request);
				return redirect(Constant.PATH_RENTER + "userInfo.htm", request);
			}
		}

		String fromUserName = getFromUserName(request);

		String nameL = request.getParameter("nameL");
		String phone = request.getParameter("phone");
		String idcard = request.getParameter("idcard");
		if (StringUtils.isNotBlank(idcard))
			idcard = idcard.toUpperCase();// 身份证的字母都要是大写
		String enote = request.getParameter("newEnote");
		log.debug("name: " + nameL + ", phone: " + phone + ", idcard: " + idcard + ", enote: " + enote);

		User renter = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("idcard", idcard);

		try {
			renter = this.renterService.loadUser(map);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		map.put("nameL", nameL);
		map.put("phone", phone);
		map.put("enote", enote);
		map.put("create_date", new Date());
		map.put("wx_userid", fromUserName);
		if (null == renter) {
			// 现在我们系统不能新增，只能通过接口让别人主动推送房客信息过来
			// try {
			// renter = renterService.saveUser(map);
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			log.info("此身份证号码还没有推送到本系统");
			alert("此身份证号码还没有推送到本系统", request);
		} else if (StringUtils.isNotBlank(fromUserName)) {
			renter.setFromUserName(fromUserName);
			try {
				Map<String, String> postParam = new HashMap<String, String>();
				postParam.put("phone", phone);// 手机号码MD5加密
				postParam.put("wxNum", fromUserName);// 微信号码
				postParam.put("twoCard", idcard);// 身份证号码MD5加密
				postParam.put("dzLabel", enote);// 电子标签号
				String jsonStr = HttpUtils.post(eRentPath + "wxRegister/wxKRegister", postParam);
				log.info("接口房客注册结果：" + jsonStr);
				// 读取JSON数据
				// ObjectMapper mapper = new ObjectMapper();
				// Map<String, Object> json=mapper.readValue(jsonStr,Map.class);
				Map<String, Map<String, String>> json = (Map<String, Map<String, String>>) JSON.parse(jsonStr);
				Map<String, String> result = (Map<String, String>) json.get("result");
				String flag = result.get("flag");
				if ("0".equals(flag)) {
					map.put("id", renter.getUserId());
					renterService.updateEnote(map);
				} else {
					log.info("接口注册失败，本地不进行注册。");
					alert(result.get("msg"), request);
					renter = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (null != renter) {
			request.getSession().setAttribute(RENTER, renter);
			map.put("namel", (String) map.get("nameL"));
			map.put("phoneHidden", renter.getUserPhone().replaceAll("(.+).{4}(.{4})", "$1****$2"));
			map.put("idcardHidden", ((String) map.get("idcard")).replaceAll("(.+).{10}(.{4})", "$1**********$2"));
			request.getSession().setAttribute("renterInfo", map);
			return redirect(Constant.PATH_RENTER + "userInfo.html", request);
		}

		return redirect(Constant.PATH_RENTER + "userInfo.htm", request);
	}

	@RequestMapping(value = "/delCRegister.json")
	@ResponseBody
	public Map<String, String> delCRegister(HttpServletRequest request, HttpServletResponse response) {
		String fromUserName = getFromUserName(request);

		String phone = request.getParameter("phone");
		String idcard = request.getParameter("idcard");
		if (StringUtils.isNotBlank(idcard))
			idcard = idcard.toUpperCase();// 身份证的字母都要是大写
		String enote = request.getParameter("enote");

		try {
			Map<String, String> postParam = new HashMap<String, String>();
			postParam.put("phone", phone);// 手机号码MD5加密
			postParam.put("wxNum", fromUserName);// 微信号码
			postParam.put("twoCard", idcard);// 身份证号码MD5加密
			postParam.put("dzLabel", enote);// 电子标签号
			String jsonStr = HttpUtils.post(eRentPath + "wxRegister/wxDelCRegister", postParam);
			log.info("接口解绑结果：" + jsonStr);
			// 读取JSON数据
			// ObjectMapper mapper = new ObjectMapper();
			// Map<String, Object> json=mapper.readValue(jsonStr,Map.class);
			Map<String, Map<String, String>> json = (Map<String, Map<String, String>>) JSON.parse(jsonStr);
			Map<String, String> result = (Map<String, String>) json.get("result");
			log.info(result.get("msg"));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 重新下发
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/wxKUpStatus.json")
	@ResponseBody
	public Map<String, String> wxKUpStatus(HttpServletRequest request, HttpServletResponse response) {
		// 微信号
		String fromUserName = getFromUserName(request);
		// 手机号
		String phone = request.getParameter("phone");
		// 身份证号
		String idcard = request.getParameter("idcard");
		// 电子标签
		String enote = request.getParameter("enote");
		if (StringUtils.isNotBlank(idcard))
			idcard = idcard.toUpperCase();// 身份证的字母都要是大写

		try {
			Map<String, String> postParam = new HashMap<String, String>();
			postParam.put("phone", phone);// 手机号码MD5加密
			postParam.put("wxNum", fromUserName);// 微信号码
			postParam.put("twoCard", idcard);// 身份证号码MD5加密
			postParam.put("dzLabel", enote);// 电子标签号
			String jsonStr = HttpUtils.post(eRentPath + "wxRegister/wxKUpStatus", postParam);
			log.info("重新下发结果：" + jsonStr);
			// 读取JSON数据
			// ObjectMapper mapper = new ObjectMapper();
			// Map<String, Object> json=mapper.readValue(jsonStr,Map.class);
			Map<String, Map<String, String>> json = (Map<String, Map<String, String>>) JSON.parse(jsonStr);
			Map<String, String> result = (Map<String, String>) json.get("result");
			log.info(result.get("msg"));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 重新绑定
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/rebind.htm")
	public String rebind(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		String fromUserName = getFromUserName(request);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("wx_userid", fromUserName);
		try {
			List<Map<String, Object>> renterList = this.renterService.findRenter(map);
			if (null != renterList && !renterList.isEmpty()) {
				request.getSession().setAttribute("renterInfo", renterList.get(0));
			}
			this.renterService.clearWxId(map);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return this.redirect(Constant.PATH_RENTER + "register.html", request);
	}
	
	
	
	/**
	 * 更改手机号码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/wxUpdateCPhone.json")
	@ResponseBody
	public Map<String, String> updatePhone(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> result = new HashMap<String, String>();
		String code = request.getParameter("code");
		if (!BooleanUtils.toBoolean(validateCode(code, true, request))) {
			// 验证不通过
			result.put("flag", "1");
			result.put("msg", "验证码不正确");
			return result;
		}
		
		// 微信号
		String fromUserName = getFromUserName(request);
		// 手机号
		String phone = request.getParameter("phone");
		// 新手机号
		String newPhone = request.getParameter("newPhone");
		// 身份证号
		String idcard = null;

		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("wx_userid", fromUserName);
		Map<String, Object> renter = null;
		try {
			List<Map<String, Object>> renterList = this.renterService.findRenter(condition);
			if (null != renterList && !renterList.isEmpty()) {
				renter = renterList.get(0);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if (null == renter) {
			log.info("用户不存在 wx_userid: " + fromUserName);
			result.put("flag", "1");
			result.put("msg", "用户不存在");
			return result;
		}
		idcard = (String) renter.get("idcard");// 身份证的字母都要是大写

		try {
			Map<String, String> postParam = new HashMap<String, String>();
			postParam.put("oldPhone", phone);// 老手机号
			postParam.put("newPhone", newPhone);// 新手机号
			postParam.put("wxNum", fromUserName);// 微信号码
			postParam.put("twoCard", idcard);// 身份证号码MD5加密
			String jsonStr = HttpUtils.post(eRentPath + "wxRegister/wxUpdateCPhone", postParam);
			log.info("更改手机号码：" + jsonStr);
			Map<String, Map<String, String>> json = (Map<String, Map<String, String>>) JSON.parse(jsonStr);
			result = (Map<String, String>) json.get("result");
			log.info(result.get("msg"));
			
			String flag = result.get("flag");
			if ("0".equals(flag)) {
				renterService.updateUserPhone(newPhone, fromUserName);
			} else {
				log.info("调用接口修改手机号失败");
				alert(result.get("msg"), request);
			}

			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 打开完善信息页面
	 * 
	 * @param renter
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/improveInformation.htm", method = { RequestMethod.GET })
	public String improveInformation(@ModelAttribute(RENTER) User renter, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("grant_id", renter.getUserId());
		try {
			Map<String, Object> personalInformation = this.renterService.findPersonalInformation(condition);
			Map<String, Object> residenceInformation = this.renterService.findResidenceInformation(condition);
			Map<String, Object> careerBreedingInformation = this.renterService.findCareerBreedingInformation(condition);
			Map<String, Object> relatedInformation = this.renterService.findRelatedInformation(condition);

			request.setAttribute("personalInformation", personalInformation);
			request.setAttribute("residenceInformation", residenceInformation);
			request.setAttribute("careerBreedingInformation", careerBreedingInformation);
			request.setAttribute("relatedInformation", relatedInformation);
			String currIndex = "-1";
			if (null == personalInformation || null == personalInformation.get("id"))
				currIndex = "0";
			else if (null == residenceInformation || null == residenceInformation.get("id"))
				currIndex = "1";
			else if (null == careerBreedingInformation || null == careerBreedingInformation.get("id"))
				currIndex = "2";
			else if (null == relatedInformation || null == relatedInformation.get("id"))
				currIndex = "3";
			request.setAttribute("currIndex", currIndex);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return this.forward(Constant.PATH_RENTER + "improveInformation.html");
	}

	/**
	 * 打开完善信息页面
	 * 
	 * @param renter
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/saveImproveInformation.json", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> saveImproveInformation(@ModelAttribute(RENTER) User renter, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("success", Boolean.FALSE);

		String informationType = request.getParameter("informationType");
		String id = request.getParameter("id");

		// 如果id，则创建update的查询条件
		Map<String, Object> condition = null;
		if (StringUtils.isNotBlank(id)) {
			condition = new HashMap<String, Object>();
			condition.put("id", NumberUtils.toLong(id, -1));
		}

		long pk = -1;
		try {
			if ("personalInformation".equals(informationType)) {
				pk = this.savePersonalInformation(renter.getUserId(), request, condition);
			} else if ("residenceInformation".equals(informationType)) {
				pk = this.saveResidenceInformation(renter.getUserId(), request, condition);
			} else if ("careerBreedingInformation".equals(informationType)) {
				pk = this.saveCareerBreedingInformation(renter.getUserId(), request, condition);
			} else if ("relatedInformation".equals(informationType)) {
				pk = this.saveRelatedInformation(renter.getUserId(), request, condition);
			}
			if (StringUtils.isBlank(id))
				json.put("pk", pk);
			if (-1 != pk)
				json.put("success", Boolean.TRUE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	/**
	 * 保存个人基本信息
	 * 
	 * @param grant_id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private long savePersonalInformation(int grant_id, HttpServletRequest request, Map<String, Object> condition)
			throws Exception {
		Map<String, Object> personalInformation = new HashMap<String, Object>();
		personalInformation.put("grant_id", grant_id);
		personalInformation.put("name", request.getParameter("name"));
		personalInformation.put("nationality", request.getParameter("nationality"));
		personalInformation.put("sex", request.getParameter("sex"));
		personalInformation.put("phone", request.getParameter("phone"));
		personalInformation.put("height", request.getParameter("height"));
		personalInformation.put("birthday", request.getParameter("birthday"));
		personalInformation.put("army_status", request.getParameter("army_status"));
		personalInformation.put("politics_status", request.getParameter("politics_status"));
		personalInformation.put("idcard", request.getParameter("idcard"));
		personalInformation.put("marital_status", request.getParameter("marital_status"));
		personalInformation.put("net_contact", request.getParameter("net_contact"));
		personalInformation.put("education", request.getParameter("education"));
		personalInformation.put("address", request.getParameter("address"));
		personalInformation.put("vehicle", request.getParameter("vehicle"));
		personalInformation.put("license_no", request.getParameter("license_no"));
		if (null == condition)
			return this.renterService.savePersonalInformation(personalInformation);
		this.renterService.updatePersonalInformation(personalInformation, condition);
		return (Long) condition.get("id");
	}

	/**
	 * 保存居住信息
	 * 
	 * @param grant_id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private long saveResidenceInformation(int grant_id, HttpServletRequest request, Map<String, Object> condition)
			throws Exception {
		Map<String, Object> residenceInformation = new HashMap<String, Object>();
		residenceInformation.put("grant_id", grant_id);
		residenceInformation.put("address", request.getParameter("address"));
		residenceInformation.put("main_phone", request.getParameter("main_phone"));
		residenceInformation.put("main_name", request.getParameter("main_name"));
		residenceInformation.put("regist_status", request.getParameter("regist_status"));
		residenceInformation.put("main_idcard", request.getParameter("main_idcard"));
		residenceInformation.put("source", request.getParameter("source"));
		residenceInformation.put("type", request.getParameter("type"));
		residenceInformation.put("category", request.getParameter("category"));
		residenceInformation.put("reasons", request.getParameter("reasons"));
		residenceInformation.put("reach_date", request.getParameter("reach_date"));
		residenceInformation.put("dwell_time", request.getParameter("dwell_time"));
		residenceInformation.put("regist_date", request.getParameter("regist_date"));
		if (null == condition)
			return this.renterService.saveResidenceInformation(residenceInformation);
		this.renterService.updateResidenceInformation(residenceInformation, condition);
		return (Long) condition.get("id");

	}

	/**
	 * 保存就业计生信息
	 * 
	 * @param grant_id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private long saveCareerBreedingInformation(int grant_id, HttpServletRequest request, Map<String, Object> condition)
			throws Exception {
		Map<String, Object> careerBreedingInformation = new HashMap<String, Object>();
		careerBreedingInformation.put("grant_id", grant_id);
		careerBreedingInformation.put("service_name", request.getParameter("service_name"));
		careerBreedingInformation.put("service_addredd", request.getParameter("service_addredd"));
		careerBreedingInformation.put("unit_phone", request.getParameter("unit_phone"));
		careerBreedingInformation.put("unit_type", request.getParameter("unit_type"));
		careerBreedingInformation.put("work_date", request.getParameter("work_date"));
		careerBreedingInformation.put("labor_contract", request.getParameter("labor_contract"));
		careerBreedingInformation.put("children_num", request.getParameter("children_num"));
		careerBreedingInformation.put("insurance", request.getParameter("insurance"));
		careerBreedingInformation.put("marry_birth_cer", request.getParameter("marry_birth_cer"));
		careerBreedingInformation.put("marry_birth_cerno", request.getParameter("marry_birth_cerno"));
		if (null == condition)
			return this.renterService.saveCareerBreedingInformation(careerBreedingInformation);
		this.renterService.updateCareerBreedingInformation(careerBreedingInformation, condition);
		return (Long) condition.get("id");
	}

	/**
	 * 保存主要关系人信息
	 * 
	 * @param grant_id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private long saveRelatedInformation(int grant_id, HttpServletRequest request, Map<String, Object> condition)
			throws Exception {
		Map<String, Object> relatedInformation = new HashMap<String, Object>();
		relatedInformation.put("grant_id", grant_id);
		relatedInformation.put("name", request.getParameter("name"));
		relatedInformation.put("sex", request.getParameter("sex"));
		relatedInformation.put("birthday", request.getParameter("birthday"));
		relatedInformation.put("idcard", request.getParameter("idcard"));
		relatedInformation.put("relation", request.getParameter("relation"));
		relatedInformation.put("work_address", request.getParameter("work_address"));
		if (null == condition)
			return this.renterService.saveRelatedInformation(relatedInformation);
		this.renterService.updateRelatedInformation(relatedInformation, condition);
		return (Long) condition.get("id");
	}

	@RequestMapping(value = "/login.htm")
	public String login(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(RENTER);// 清除登陆用户信息
		model.remove(RENTER);

		String phone = request.getParameter("phone");
		String fromUserName = getFromUserName(request);
		log.info("phone: " + phone + ", fromUserName: " + fromUserName);
		if (StringUtils.isBlank(phone) && StringUtils.isNotBlank(fromUserName)) {
			// 微信登陆
			try {
				phone = this.renterService.findPhone(fromUserName);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (StringUtils.isBlank(phone)) {
			// 到注册页面
			log.info("没关联，跳转到注册页面");
			return redirect(Constant.PATH_RENTER + "register.html", request);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		try {
			User user = this.renterService.loadUser(map);
			if (null != user) {
				if (StringUtils.isBlank(user.getFromUserName())) {
					// 到注册页面
					log.info("没关联，跳转到注册页面");
					return redirect(Constant.PATH_RENTER + "register.html", request);
				}
				user.setFromUserName(fromUserName);
				// model.addAttribute(RENTER, user);
				request.getSession().setAttribute(RENTER, user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return redirect(Constant.PATH_RENTER + "communityList.htm", request);
	}

	@RequestMapping(value = "/findArea.htm")
	public void findArea(@RequestParam("city") String parentId, @RequestParam("level") String level,
			HttpServletRequest request, HttpServletResponse response) {
		List<Map<String, Object>> areaList = null;
		try {
			areaList = findArea(NumberUtils.toInt(parentId), NumberUtils.toInt(level));
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.toJson(response, areaList);
	}

	@RequestMapping(value = "/findStreet.htm")
	public void findStreet(@RequestParam("area") String area, HttpServletRequest request,
			HttpServletResponse response) {
		List<Map<String, Object>> streetList = null;
		try {
			streetList = findStreet(area);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.toJson(response, streetList);
	}

	@RequestMapping(value = "/findDept.htm")
	public void findDept(@RequestParam("street_id") String street_id, HttpServletRequest request,
			HttpServletResponse response) {
		List<Map<String, Object>> deptList = null;
		try {
			deptList = findDept(NumberUtils.toInt(street_id));
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.toJson(response, deptList);
	}

	@RequestMapping(value = "/findCommunity.htm")
	public void findCommunity(@RequestParam("dept_id") String dept_id, HttpServletRequest request,
			HttpServletResponse response) {
		List<Map<String, Object>> deptList = null;
		try {
			deptList = findCommunity(NumberUtils.toInt(dept_id));
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.toJson(response, deptList);
	}

	@RequestMapping(value = "/communityList.htm")
	public String communityList(@RequestParam(value = "city", required = false) String city,
			@RequestParam(value = "area", required = false) String area,
			@RequestParam(value = "street_id", required = false) String street_id,
			@RequestParam(value = "dept_id", required = false) String dept_id,
			@RequestParam(value = "community_id", required = false) String community_id,
			@RequestParam(value = "keywords", required = false) String keywords, Pager pager,
			@ModelAttribute(RENTER) User renter, HttpServletRequest request, HttpServletResponse response) {
		// log.debug("renterId: " + renterId);
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(keywords)) {
			map.put("name", "%" + keywords + "%");
			map.put("dname", "%" + keywords + "%");
		}
		if (StringUtils.isNotBlank(community_id) && !"0".equals(community_id)) {
			map.put("id", community_id);
		}
		if (StringUtils.isNotBlank(dept_id) && !"0".equals(dept_id)) {
			map.put("dept_id", dept_id);
		}
		if (StringUtils.isNotBlank(street_id) && !"0".equals(street_id)) {
			map.put("street_id", street_id);
		}
		if (StringUtils.isNotBlank(area) && !"0".equals(area)) {
			map.put("area", area);
		}
		if (StringUtils.isNotBlank(city) && !"0".equals(city)) {
			map.put("city", city);
		}

		Pager allCommunity = null;
		try {
			allCommunity = this.renterService.findAllCommunity(map, pager.getPageNo(), pager.getPageSize());
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("city", city);
		request.setAttribute("area", area);
		request.setAttribute("street_id", street_id);
		request.setAttribute("dept_id", dept_id);
		request.setAttribute("community_id", community_id);
		request.setAttribute("keywords", keywords);
		request.setAttribute(PAGER_MODEL, allCommunity);
		return Constant.PATH_RENTER + "communityList";
	}

	@RequestMapping(value = "/{communityId}/roomList.htm")
	public String roomList(@PathVariable("communityId") String communityId, HttpServletRequest request,
			HttpServletResponse response) {
		log.debug("communityId: " + communityId);
		List<Map<String, Object>> communityRoom = null;
		try {
			communityRoom = this.renterService.findRoomByCommunityId(NumberUtils.toInt(communityId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String communityName = (String) getCommunityValue(communityId, "name");// 小区名
		String deptId = getCommunityValue(communityId, "dept_id") + "";
		String departmentName = (String) getDepartmentValue(deptId, "name");// 社区名
		request.setAttribute("address", departmentName + " " + communityName);
		request.setAttribute("rooms", communityRoom);
		return Constant.PATH_RENTER + "roomList";
	}

	@RequestMapping(value = "/{communityId}/{roomId}/bedList.htm")
	public String bedList(@PathVariable("communityId") String communityId, @PathVariable("roomId") String roomId,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("communityId: " + communityId + ", roomId: " + roomId);
		List<Map<String, Object>> roomBed = null;
		try {
			roomBed = renterService.findBedByRoomId(NumberUtils.toInt(roomId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String communityName = (String) getCommunityValue(communityId, "name");// 小区名
		String deptId = getCommunityValue(communityId, "dept_id") + "";
		String departmentName = (String) getDepartmentValue(deptId, "name");// 社区名
		String roomName = "";// 房屋名

		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("id", roomId);
		try {
			Map<String, Object> room = this.renterService.findRoom(condition);
			roomName = (String) room.get("building") + (String) room.get("unit") + (String) room.get("room_num");
		} catch (Exception e) {
			e.printStackTrace();
		}

		request.setAttribute("address", departmentName + " " + communityName + " " + roomName);
		request.setAttribute("beds", roomBed);
		return Constant.PATH_RENTER + "bedList";
	}

	@RequestMapping(value = "/{communityId}/{roomId}/{bedId}/order.htm")
	public String order(@PathVariable("communityId") String communityId, @PathVariable("roomId") String roomId,
			@PathVariable("bedId") String bedId, HttpServletRequest request, HttpServletResponse response) {
		log.debug("communityId: " + communityId + ", roomId: " + roomId + ", bedId: " + bedId);
		Map<String, Object> bed = null;
		Map<String, Object> room = null;
		Double rental = 0.0D;
		Integer deposit = 2;
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id", roomId);
			room = renterService.findRoom(condition);// 查房间
			rental = (Double) room.get("room_price");
			deposit = (Integer) room.get("deposit");
			if (StringUtils.isNotBlank(bedId) && NumberUtils.toInt(bedId) > 0) {
				condition.put("id", bedId);
				bed = renterService.findBed(condition);// 查床位
				rental = (Double) bed.get("bed_price");
				deposit = (Integer) bed.get("deposit");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String communityName = (String) getCommunityValue(communityId, "name");// 小区名
		String deptId = getCommunityValue(communityId, "dept_id") + "";
		String departmentName = (String) getDepartmentValue(deptId, "name");// 社区名
		String roomName = "";// 房屋名
		String bedName = "";// 床位名

		roomName = (String) room.get("building") + (String) room.get("unit") + (String) room.get("room_num");
		if (null != bed) {
			bedName = (String) bed.get("bed_num");
		}

		request.setAttribute("mainId", room.get("main_id"));
		request.setAttribute("address", departmentName + " " + communityName);
		request.setAttribute("roomName", roomName);
		request.setAttribute("bedName", bedName);
		request.setAttribute("serviceFee", Constant.SERVICE_FEE);// 服务费
		request.setAttribute("rental", rental);// 租金
		request.setAttribute("deposit", deposit);// 押金（月）
		return Constant.PATH_RENTER + "order";
	}

	@RequestMapping(value = "/saveOrder.htm")
	public String saveOrder(@RequestParam String communityId, @RequestParam String roomId, @RequestParam String bedId,
			@RequestParam Integer tenancy, @ModelAttribute(RENTER) User renter, HttpServletRequest request,
			HttpServletResponse response) {
		// 先调接口的绑定房客
		try {
			Map<String, Object> bedGrantDel = new HashMap<String, Object>();
			bedGrantDel.put("roomId", roomId);
			bedGrantDel.put("classId", roomId);
			bedGrantDel.put("bedId", bedId);
			bedGrantDel.put("grantId", renter.getUserId());
			Map<String, String> wxDelBedGrant = this.eRentService.wxDelBedGrant(bedGrantDel);
			if ("1".equals(wxDelBedGrant.get("flag"))) {
				log.error("接口绑定房客失败 roomId: " + roomId + ", bedId: " + bedId + ", grantId: " + renter.getUserId());
				return redirect(Constant.PATH_RENTER + "orderList.htm", request);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			return redirect(Constant.PATH_RENTER + "orderList.htm", request);
		}
		
		this.order(communityId, roomId, bedId, request, response);// 重新查询租金等参数

		Double rental = (Double) request.getAttribute("rental");// 租金
		Integer deposit = (Integer) request.getAttribute("deposit");// 押金（月）
		Double totalPrice = (rental + Constant.SERVICE_FEE) * tenancy + deposit * rental;// 总价=租金+服务费+总押金
		String address = (String) request.getAttribute("address");// 地址
		String roomName = (String) request.getAttribute("roomName");// 房号
		String bedName = (String) request.getAttribute("bedName");// 床号
		String mainId = (String) request.getAttribute("mainId");// 房主ID

		Date today = new Date();
		final String orderId = createOrderId();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", orderId);// 订单号
		map.put("grant_id", renter.getUserId());// 租客ID
		map.put("main_id", mainId);// 房主ID
		map.put("room_id", roomId);// 房间ID
		if (StringUtils.isNotBlank(bedId) && NumberUtils.toInt(bedId) > 0)
			map.put("bed_id", bedId);// 床ID
		map.put("tenancy", tenancy);// 租期（月）
		map.put("service_fee", Constant.SERVICE_FEE);// 服务费
		map.put("rental", rental);// 租金
		map.put("deposit", deposit);// 押金（月）
		map.put("total_price", totalPrice);// 总价
		map.put("create_date", today);// 创建时间
		map.put("expires_date", DateUtils.addMonths(today, tenancy));// 到期时间
		map.put("detail",
				address + " " + roomName + " " + bedName + " 押" + deposit + "付" + tenancy + "，总共支付" + totalPrice + "元");// 订单详情
		map.put("state", Constant.ORDER_STATE_CONFIRMING);// 创建时间

		boolean saveOrderSuccess = false;
		boolean updateBedSuccess = false;
		try {
			saveOrderSuccess = this.renterService.saveOrder(map);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (saveOrderSuccess) {
			log.info("更新床位状态为“待确认”");
			// 同时更新床位状态
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("is_rent", Constant.BED_STATE_RENTED);
			data.put("grant_id", renter.getUserId());
			data.put("room_id", roomId);
			if (StringUtils.isNotBlank(bedId) && NumberUtils.toInt(bedId) > 0) {
				data.put("id", bedId);
			}
			try {
				updateBedSuccess = renterService.updateBedState(data);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (updateBedSuccess) {
			// 给房主发短信通知
			User master = null;
			Map<String, Object> userQuery = new HashMap<String, Object>();
			userQuery.put("id", mainId);
			try {
				master = this.masterService.loadUser(userQuery);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			String mainPhone = master.getUserPhone();// 房主手机号

			try {
				smsService.saveSms(null, mainPhone, "“" + renter.getUserName() + "”下单租了您的“" + address + " " + roomName
						+ " " + bedName + "”，请登陆“云i租”进行处理。");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return redirect(Constant.PATH_RENTER + "orderList.htm", request);
	}

	/**
	 * 生成订单号
	 * 
	 * @return
	 */
	private String createOrderId() {
		return DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + RandomStringUtils.randomNumeric(4);
	}

	@RequestMapping(value = "/orderList.htm")
	public String orderList(Pager pager, @ModelAttribute(RENTER) User renter, HttpServletRequest request,
			HttpServletResponse response) {
		if (null != renter) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("grant_id", renter.getUserId());

			Pager myOrder = null;
			try {
				myOrder = this.renterService.findMyOrder(map, pager.getPageNo(), pager.getPageSize());
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute(PAGER_MODEL, myOrder);
		}
		return Constant.PATH_RENTER + "orderList";
	}

	/**
	 * 取消订单
	 * 
	 * @param orderId
	 * @param renter
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/{orderId}/cancel.htm")
	@ResponseBody
	public String cancel(@PathVariable String orderId, @ModelAttribute(RENTER) User renter, HttpServletRequest request,
			HttpServletResponse response) {
		log.info("用户" + renter.getUserId() + " 取消订单" + orderId);
		Boolean success = false;
		Map<String, Object> order = null;
		if (null != renter) {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("state", Constant.ORDER_STATE_CANCEL);
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id", orderId);
			condition.put("grant_id", renter.getUserId());

			try {
				success = this.renterService.updateMyOrder(data, condition);
				if (success) {
					order = renterService.findOrder(condition);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (success && null != order) {
			log.info("更新床位状态为“已取消”");
			String bedId = order.get("bed_id") + "";
			// 同时更新床位状态
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("is_rent", Constant.BED_STATE_NORENT);
			data.put("grant_id", null);
			data.put("room_id", order.get("room_id"));
			if (StringUtils.isNotBlank(bedId) && NumberUtils.toInt(bedId) > 0) {
				data.put("id", bedId);
			}
			try {
				renterService.updateBedState(data);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return success.toString();
	}

	@RequestMapping(value = "/getOpenidByCode.htm")
	@ResponseBody
	protected String getOpenidByCode(@RequestParam(value = "openacc") String openacc,
			@RequestParam(value = "code") String code) {
		return super.getOpenidByCode(openacc, code);
	}

}
